package com.wenshi.web.service.impl;

import com.wenshi.common.core.domain.AjaxResult;
import com.wenshi.system.domain.SysDevice;
import com.wenshi.system.service.ISysDeviceService;
import com.wenshi.web.netty.ModbusClient;
import com.wenshi.web.service.webService;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;


@Service
public class webServiceImpl implements webService {
    @Autowired
    ISysDeviceService sysDeviceService;
    @Autowired
    ModbusClient modbusClient;
    @Override
    public CompletableFuture<AjaxResult> connectDeviceByAddress(SysDevice sysDevice) {
        CompletableFuture<AjaxResult> resultFuture = new CompletableFuture<>();
        if (sysDevice.isDeviceStatus()){
            sysDevice.setDeviceStatus(false);
            sysDeviceService.updateById(sysDevice);
            modbusClient.discConnect(sysDevice.getDeviceIp());
            resultFuture.complete(AjaxResult.success());
        }else {
            int devicePort = sysDevice.getDevicePort().intValue();
            ChannelFuture channelFuture = modbusClient.doConnect(sysDevice.getDeviceIp(),devicePort);

            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()){
                        sysDevice.setDeviceStatus(true);
                        sysDeviceService.updateById(sysDevice);
                        resultFuture.complete(AjaxResult.success("连接成功"));
                    }else {
                        resultFuture.complete(AjaxResult.error("连接失败"));
                    }
                }
            });
        }
        return resultFuture;
    }

    @Override
    public void connectDeviceInit() {
        List<SysDevice> list = sysDeviceService.list();
//        List<SysDevice> connectList=new ArrayList<>();
//        for (SysDevice sysDevice : list) {
//            if (sysDevice.isDeviceStatus()==true){
//                connectList.add(sysDevice);
//            }
//        }
//        for (SysDevice sysDevice : connectList) {
//            modbusClient.doConnect(sysDevice.getDeviceIp());
//        }
//
        List<SysDevice> collect = list.stream().filter(SysDevice::isDeviceStatus).collect(Collectors.toList());
        collect.forEach(sysDevice -> {modbusClient.doConnect(sysDevice.getDeviceIp(),sysDevice.getDevicePort().intValue());});
    }
}
